import { defineStore } from 'pinia'
import { getOrders, createOrder, updateOrderStatus, shipOrder } from '@/api/order'
import { ElMessage } from 'element-plus'

export const useOrderStore = defineStore('order', {
  state: () => ({
    orders: [],
    total: 0
  }),

  actions: {
    // 获取订单列表
    async getOrders(params) {
      try {
        console.log('开始获取订单列表，参数:', params)
        const res = await getOrders(params)
        console.log('订单列表响应:', res)

        if (res.code === 200) {
          // 处理不同的响应格式
          if (Array.isArray(res.data)) {
            this.orders = res.data
            this.total = res.data.length
          } else if (res.data && res.data.records) {
            this.orders = res.data.records
            this.total = res.data.total
          } else if (res.data) {
            this.orders = [res.data]
            this.total = 1
          } else {
            this.orders = []
            this.total = 0
          }
          return res.data
        }
        throw new Error(res.message || '获取订单列表失败')
      } catch (error) {
        console.error('获取订单列表失败:', error)
        ElMessage.error(error.message || '获取订单列表失败')
        this.orders = []
        this.total = 0
        throw error
      }
    },

    // 创建订单
    async createOrder(data) {
      try {
        console.log('创建订单，数据:', data)
        const res = await createOrder(data)
        if (res.code === 200) {
          ElMessage.success('创建订单成功')
          await this.getOrders()
          return res.data
        }
        throw new Error(res.message || '创建订单失败')
      } catch (error) {
        console.error('创建订单失败:', error)
        ElMessage.error(error.message || '创建订单失败')
        throw error
      }
    },

    // 更新订单状态
    async updateOrderStatus(id, status) {
      try {
        console.log('更新订单状态，ID:', id, '状态:', status)
        const res = await updateOrderStatus(id, status)
        if (res.code === 200) {
          ElMessage.success('更新订单状态成功')
          await this.getOrders()
          return res.data
        }
        throw new Error(res.message || '更新订单状态失败')
      } catch (error) {
        console.error('更新订单状态失败:', error)
        ElMessage.error(error.message || '更新订单状态失败')
        throw error
      }
    },

    // 发货
    async shipOrder(orderId, shipData) {
      try {
        console.log('订单发货，ID:', orderId, '发货数据:', shipData)
        const res = await shipOrder(orderId, shipData)
        if (res.code === 200) {
          ElMessage.success('订单发货成功')
          await this.getOrders()
          return res.data
        }
        throw new Error(res.message || '订单发货失败')
      } catch (error) {
        console.error('订单发货失败:', error)
        ElMessage.error(error.message || '订单发货失败')
        throw error
      }
    }
  }
}) 